<?php
/**
 * 下载 仅 发布者 可以下载
 * 
 * 下载方式 通过 发布者 搜索 code 进行下载 
 * 
 * 下载 选项 filetype 为 
 * 
 * */
session_start();

include("config.php");
$dbconf=new DBConfig();
$conn= new mysqli($dbconf->servername,$dbconf->username,$dbconf->password,$dbconf->dbname);
if ($conn->connect_error) {
	   // die("mysql连接失败: " . $conn->connect_error);
	   $reqData->status='error';
	   $reqData->type='mysql';
}
//echo $_SESSION['apikey'];
if(@$_SESSION['apikey']==''||@$_SESSION['apikey']=='guest'||@$_SESSION['apikey']!=@$_GET['apikey']){
	if(@$_GET['apikey']){
//		require('loginOfApikey.php');
		$apikey=$_GET['apikey'];
	//查询 数据库是否存在 apikey 如果 存在 则 则证明 用户信息 是有效额 
	//有效 则 直接 返回 apikey 否则 进行  后面的步骤
		$sql="SELECT * FROM `user` WHERE apikey='$apikey'";
		$result = $conn->query($sql);
		if($result->num_rows>0){
			//查询 数据 库 返回的是 查询到的结果有 几条 
			//如果 大于 0 条  意味着存在这条数据 表面 数据有效 则 输出信息		
//			$reqData->status='success';
//			$reqData->apikey=$apikey;
			$row =$result->fetch_assoc();
			$_SESSION['apikey']=$row['apikey'];
			$_SESSION['userid']=$row['userid'];
		}
	}
}

class ReqDataType{
	public $status='error';
	public $type='Download';
	public $tableType='NOT';
	public $msg;
}

class ProcDown{
	public $tableJson;
	public $titlename;
	public $csv_body;
	public $csv_head;
	public $reqDataType;
	public $conn;
	
	function Init($conn){
		$this->conn=$conn;
		$this->reqDataType=new ReqDataType();
	}
	//获取 
	function getTitleMsg($code){
		@$sql="SELECT * FROM `tablelist` WHERE mask ='$code' and userid='".$_SESSION['userid']."';";
		$conn=$this->conn;
//		echo $sql;
		$result = $conn->query($sql);
		if($result->num_rows>0){
			$row =$result->fetch_assoc();
			$this->tableJson=json_decode($row['tablejson']);
			$this->titlename=$row['title'];
			$this->reqDataType->msg='get tableMsg success';
			$this->reqDataType->status='success';
//			print_r($this->tableJson);
		}else{
			$this->reqDataType->msg='code error';
			$this->reqDataType->status='error';
		}
//		echo $this->tableid;
		return $this->titlename;
	}
	
	function getTableDatalist(){
		$listArray=array();
		@$this->csv_head=$this->tableJson->rowlist;//iconv( 'UTF-8', 'GB2312//IGNORE', $this->tableJson->rowlist );
		//$this->choosename=$this->tablejson->rowlist[0];
		@$sql = "SELECT * FROM `I_tebles`.`".$this->tableJson->tableid."`";
		$conn=$this->conn;
		$result = $conn->query($sql);
//		$chooselistTemp=array();
//		 echo $sql;
		if (@$result->num_rows > 0) {
		    // 输出数据
//		    echo "{\"data\":[";
		    while($row = $result->fetch_assoc()) {
//		        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
//				
				$rows=[];
				foreach($row as $key=>$val)
				{
					$rows[]=iconv( 'UTF-8', 'GB2312//IGNORE', $val );
				}	
				//$this->chooselist[]=$row[$this->choosename];
				//$row[];
				$listArray[]= $rows;
		    }
		    
		    $this->reqDataType->msg='get databody success';
		    $this->reqDataType->status='success';
//		    print_r($this->chooselist);
//		    $this->chooselist=$chooselistTemp;
//		print_r($this->tablejson);
		} else {
//		    echo "0 结果";
//			 ($this->tablejson);
			$this->reqDataType->msg='get databody error';
			$this->reqDataType->status='error';
		}
//		echo json_encode($listArray);
		$this->csv_body=$listArray;
		return ($this->csv_body);
//		echo "{}]}";
	}
	
	//csv body 是二维数组 head 是一维数组
	function createcsv($fileName,$csv_head,$csv_body)
	{
	    // 头部标题
	//  $csv_header = array();
	    $csv_header = $csv_head;
	    
	    $header = implode(',', $csv_header) . PHP_EOL;
	    $content = '';
	    foreach ($csv_body as $k => $v) {
	        $content .= implode(',', $v) . PHP_EOL;
	    }
	    $csvData = $header . $content;
	    header("Content-type:text/csv;");
	    if($fileName==""){
	    	$fileName="null";
	    }
	    header("Content-Disposition:attachment;filename=" . $fileName.".csv");
	    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
	    header('Expires:0');
	    header('Pragma:public');
	    echo $csvData;
	}
	function createDownCsvGbk(){
		
		$this->createcsv($this->titlename,$this->UTF82GBK($this->csv_head),$this->csv_body);
	}
	
	function UTF82GBK($dataArray){
		$temp=array();
		foreach($dataArray as $val){
			$temp[]=iconv( 'UTF-8', 'GB2312//IGNORE', $val );
		}
		return $temp;
	}
}


$reqData=new ReqDataType();
	//全局参数 给 后续 流程 提供 信息 载体


if(@$_GET['code']&&@$_SESSION['apikey']!='guest'){
$code=$_GET['code'];
$procDown=new ProcDown();
$procDown->Init($conn);

	//$code="f3bc0ed5e394fea3372a365f8ef12192";
$procDown->getTitleMsg($code);
$procDown->getTableDatalist();
$reqData=$procDown->reqDataType;
//print_r($procDown->UTF82GBK($procDown->csv_head));
if($procDown->reqDataType->msg=='get databody success'){
	$procDown->createDownCsvGbk();
}else{
//	echo "test!";
}
}else{
	echo json_encode($reqData);

}

?>